package cn.acewill.yxd.yunxundian.ui.sign;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.zyf.vc.ui.PlayVideoActiviy;
import com.zyf.vc.ui.RecorderActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.AddPhotoAdapter;
import cn.acewill.yxd.yunxundian.adapter.AddVideoAdapter;
import cn.acewill.yxd.yunxundian.adapter.ItemScoreAdapter;
import cn.acewill.yxd.yunxundian.componet.HorizontalListView;
import cn.acewill.yxd.yunxundian.componet.photoCrop.BitmapUtils;
import cn.acewill.yxd.yunxundian.componet.photoCrop.PopupUtil;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.r_reportrowAddtion;
import cn.acewill.yxd.yunxundian.model.r_rrowAddtion_item;
import cn.acewill.yxd.yunxundian.model.r_trrAddtion;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.user.ImageViewPagerActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.PermissionUtil;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * Created by AAA on 2017/4/21.
 */

public class MarkPhotoActivity extends BaseActivity implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener,View.OnClickListener,EasyPermissions.PermissionCallbacks {
    protected YXDAPP yxdapp = new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private TextView markTitle, markScore;
    /*用于显示评分的样式,默认设置为1*/
    private int scoreType = 1;
    /*评分的描述*/
    private EditText markDesc;
    private View backBtn;
    private Button submitBtn;
    /*展示图片的list*/
    private List<String> photoList = new ArrayList<>();
    private List<String> videoList = new ArrayList<>();
    private AddPhotoAdapter adapter;
    private AddVideoAdapter videoAdapter;
    /*用于保存拍照完后的图片或者选择图片后的完整路径*/
    private String allPhotoFileString = "";
    private String newPhotoName = "";
    /*保存的video的完整路径*/
    private String allVideoFileString = "";
    /*最后生成的图片的路径*/
    private String resultPath;
    private  List<RMain.TablesBean.RowsBean.RItemsBean> scoreList;
    private int minorId;//小项的Id;
    private double MaxScore;//最大的分数
    /*选择的分数的ID*/
    private int scoreId;
    /*scoretype!=1时的分数判断*/
    private EditText inputScore;
    //选取分数的判断
    private Dialog dialog;
    //语音输入
    private Button voiceIn;
    private RecognizerDialog iatDialog=null;
    private ProgressDialog pDialog=null;
    private boolean isFinish=false;
    private tempLostRR rr;
    private String title;
    /*判断页面跳转的标识*/
    private int tag = 0;
    /*本地数据库ID标识*/
    private int _ID;
    /*查询的数据源*/
    /*日程id*/
    private int schid;
    /*门店的名称，给拍照水印*/
    public  String shopName;
    //用户输入的评分数据
    private String score;
    private static final int DECIMAL_DIGITS = 2;
    private int ispoint;
    private LinearLayout contentLayout;
    //细项附加项列表
    private List<r_reportrowAddtion> rraList = null;
    private List<r_trrAddtion>trraList = null;
    private Handler mHandler = new iHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yxd_mark_item);
        methodRequiresPermission();

        try {
            initView();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    public void initView() throws DbException {
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        myToolBar.setTitle("");
        myToolBar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(myToolBar);
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExitDialog();
            }
        });
        this.markDesc = (EditText) findViewById(R.id.markDesc);
        this.markScore = (TextView) findViewById(R.id.markScore);
        this.markScore.setOnClickListener(this);
        this.markTitle = (TextView) findViewById(R.id.markTitle);
        this.voiceIn=(Button)findViewById(R.id.voiceIn);
        submitBtn= (Button) findViewById(R.id.submitInfo);
        submitBtn.setOnClickListener(this);
        contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
        /*相片*/
        HorizontalListView addPhotoListView = (HorizontalListView) findViewById(R.id.addPhotoListView);
        adapter = new AddPhotoAdapter(this, photoList);
        addPhotoListView.setAdapter(adapter);
        addPhotoListView.setOnItemClickListener(this);
        addPhotoListView.setOnItemLongClickListener(this);
        /*视频*/
        HorizontalListView addVideoListView = (HorizontalListView) findViewById(R.id.addVideoListView);
        videoAdapter=new AddVideoAdapter(this,videoList);
        addVideoListView.setAdapter(videoAdapter);
        /*视频的点击事件*/
        addVideoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
                newPhotoName = "yxd_video" + sdf.format(new Date());
                //视频的路径
          //    String videoResultPath=getExternalFilesDir(Environment.DIRECTORY_MOVIES).getAbsolutePath() + "/" + newPhotoName + ".mp4";
                int count = videoAdapter.getCount();
                if (position==0){
                    if (count<=1){
                     showVideoPop();
                    }else{
                        BaseActivity.showAnimaDialog(MarkPhotoActivity.this,"视频已达最大限制");
                    }
                }else {
                    //点击播放
                    startActivity(new Intent(MarkPhotoActivity.this,PlayVideoActiviy.class).putExtra("file_path",videoList.get(position-1)).putExtra("code_play",2));
                }
            }
        });
        /*视频长按删除*/
        addVideoListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    DelVideoListItem(position-1);
                }
                return false;
            }
        });
        /*获取上个页面的值*/
        getIntentData();
        getVideoPath();

        voiceIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (iatDialog != null) {
                    iatDialog.cancel();
                    iatDialog.destroy();
                }
                startDialogOnline();
            }
        });
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.muti_select_ok,menu);
//        return super.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()){
//            case R.id.action_ok:
//                submitAllInfo();
//                break;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            //Log.i("tag", "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(MarkPhotoActivity.this,"语音初始化失败",Toast.LENGTH_SHORT).show();
                //Log.e("tag", "初始化失败，错误码：" + code);
            }
        }
    };

    private void showProgressDialog() {
        pDialog = new ProgressDialog(this);

        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setProgress(100);
        pDialog.setMessage("请稍等...");
        pDialog.setIndeterminate(false);
        pDialog.show();

        WindowManager.LayoutParams lp = pDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        Window win = pDialog.getWindow();
        win.setAttributes(lp);

        new Thread(new Runnable() {

            @Override
            public void run() {
                //long startTime = System.currentTimeMillis();
                int progress = 0;

                //while (System.currentTimeMillis() - startTime < 1000) {
                //语音听写完成后，释放对话框
                while (!isFinish) {
                    try {
                        progress += 10;
                        pDialog.setProgress(progress);
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        pDialog.dismiss();
                    }
                }

                pDialog.dismiss();
                isFinish=false;
            }
        }).start();
    }

    public void startDialogOnline() {
        //1.创建SpeechRecognizer对象，第二个参数：本地听写时传InitListener
        iatDialog = new RecognizerDialog(this, mInitListener);
        //2.设置听写参数

        iatDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        iatDialog.setParameter(SpeechConstant.ACCENT, "mandarin ");


        //3.设置回调接口
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                if (!b) {
                    String json = recognizerResult.getResultString();

                    String str = jsonToHua(json);
                    markDesc.append(str);
                    //Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(SpeechError speechError) {
                //Log.e("error", speechError.toString());
            }
        });
        //4.开始听写
        iatDialog.show();
    }
/*
* {"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0.00,"w":"写"}]},{"bg":0,"cw":[{"sc":0.00,"w":"进去"}]},{"bg":0,"cw":[{"sc":0.00,"w":"了"}]},{"bg":0,"cw":[{"sc":0.00,"w":"吗"}]}]}
*
* */
public String jsonToHua(String json)
{
    StringBuilder retStr= new StringBuilder();
    try {
        JSONObject result = new JSONObject(json);
        JSONArray nameList = result.getJSONArray("ws");//获取JSONArray
        for(int i=0;i<nameList.length();i++)
        {
            JSONObject jo=nameList.getJSONObject(i);
            JSONArray ja=jo.getJSONArray("cw");
            for(int j=0;j<ja.length();j++)
            {
                retStr.append(ja.getJSONObject(j).getString("w"));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return retStr+".";

}

    public void getIntentData() {
        /*由于编辑从新进来，需要判断大小项与分数类型*/
        tag = getIntent().getIntExtra("tag", 0);
        schid=getIntent().getIntExtra("schid",0);
        ispoint=getIntent().getIntExtra("ispoint",0);
        if (tag == 1) {//由小项直接进入
            minorId = getIntent().getIntExtra("id", -1);
            MaxScore = (int) getIntent().getDoubleExtra("maxScore", -1);
            /*scoretype 可能没有，默认设置为1*/
            if (getIntent().getIntExtra("type", -1) == -1) {
                scoreType = 1;
            } else {
                scoreType = getIntent().getIntExtra("type", -1);
            }
            /*设置标题*/
            title = getIntent().getStringExtra("sName") + "\t" + getIntent().getStringExtra("title");
            markTitle.setText(title);
        }
        if (tag == 2) { //编辑
            _ID = getIntent().getIntExtra("_ID", -1);

            try {
                rr = db.selector(tempLostRR.class).where("_ID", "=", _ID + "").findFirst();
            } catch (DbException e) {
                e.getStackTrace();
            }
            minorId = rr.getRRowId();
            scoreId=rr.getSelectItemId();
            scoreType = getIntent().getIntExtra("type", -1);
            markDesc.setText(rr.getDescStr());
            score=String.valueOf(rr.getScore());
            markScore.setText(score);
            setListViewData(adapter, rr.getJpgStr());
            markTitle.setText(rr.getRowName());
            /*设置初始的图片*/
            allPhotoFileString = rr.getJpgStr();
            allVideoFileString=rr.getVideoStr();
            setVideoListData(videoAdapter,rr.getVideoStr());
        }
        try {
            initData();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /*获取评分数据*/
    public void initData() throws DbException {
        /*得到rJson*/
        Schedule schedule = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
        int shopId = schedule.getShopID();
        if(shopId>0) {
            Shop shop = db.selector(Shop.class).where("ID", "=", shopId).findFirst();
            shopName = shop.getShopName();
        }
        sType type = db.selector(sType.class).where("ID", "=", schedule.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        /*转化的到集合*/
        String json = rmian.getjSon();
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();

        ArrayList<RMain> rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        scoreList = new ArrayList<>();
        //加载评分数据
        if (tag==1){//添加评估
            scoreList=getItemsByRrowid(minorId,rMains);
        }else{//编辑
            MaxScore = getMaxScoreByRrowid(rr.getRRowId(), rMains);
            scoreList=getItemsByRrowid(rr.getRRowId(),rMains);
        }

        initRowAdd();
    }

    //region 细项附加项

    //创建文本
    private TextView createTV(String text){
        TextView textView=new TextView(this);
        textView.setText(text);
        return textView;
    }
    //创建EditText
    private EditText createET(r_reportrowAddtion rra, r_trrAddtion trra){
        EditText editText=new EditText(this);
        if(rra.getcountGroup() != 0){
            editText.setHint(rra.getdescStr()+"(请输入"+rra.getmin()+"至"+rra.getmax()+"之间的分数)");
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        }else{
            editText.setHint(rra.getdescStr());
        }
        editText.setText(trra.getitemValue());
        trra.setview(editText);
        return editText;
    }
    //创建多选
    private CheckBox createCB(String text, r_trrAddtion trra){
        CheckBox checkBox=new CheckBox(this);
        checkBox.setText(text);
        checkBox.setChecked(trra.getischecked()>0);
        trra.setview(checkBox);
        return checkBox;
    }
    //创建输入框
    private LinearLayout createInput(r_reportrowAddtion rra, r_trrAddtion trra){
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams descParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,1);
        linearLayout.addView(createTV(rra.getname()), nameParams);
        linearLayout.addView(createET(rra, trra), descParams);
        return linearLayout;
    }
    //创建单选
    private LinearLayout createSelector(int rraIndex, r_trrAddtion trra){
        LinearLayout linearLayout = new LinearLayout(this);
        List<r_rrowAddtion_item> rra_iList = null;
        int selection = 0;

        try {
            rra_iList = db.selector(r_rrowAddtion_item.class).where("r_raid", "=", rraList.get(rraIndex).getId()).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(rra_iList == null)
            return linearLayout;

        for(int i=0;i<rra_iList.size();i++){
            if(rra_iList.get(i).getId() == trra.getr_rrItemId()){
                selection = i;
            }
        }

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.addView(createTV(rraList.get(rraIndex).getname()), params);
        Spinner spinner = new Spinner(this);
        ArrayAdapter<r_rrowAddtion_item> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, rra_iList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(selection);
        trra.setview(spinner);
        linearLayout.addView(spinner, params);
        return linearLayout;
    }
    //创建分隔线
    private View createDividing(){
        View dividingView = new View(this);
        dividingView.setBackgroundColor(getResources().getColor(R.color.dg));
        LinearLayout.LayoutParams dividingParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,5);
        dividingView.setLayoutParams(dividingParams);
        return dividingView;
    }
    //创建r_trrAddtion表项
    private r_trrAddtion getTrra(r_reportrowAddtion rra){
        for(int i=0;i<trraList.size();i++){
            if(trraList.get(i).getr_rrAId() == rra.getId())
                return trraList.get(i);
        }
        r_trrAddtion trra = new r_trrAddtion();
        trra.setId(0);
        trra.setschid(schid);
        trra.setrowId(minorId);
        trra.setr_rrAId(rra.getId());
        if(rra.getcountGroup()>0)
            trra.setrights(rra.getrights());
        else
            trra.setrights(0);
        trra.setorderValue(rra.getorderValue());
        trra.setmax(rra.getmax());
        trra.setmin(rra.getmin());
        trra.setstep(rra.getstep());
        trra.setname(rra.getname());
        trra.setitemValue("");
        trra.setr_rrItemId(0);
        trra.setischecked(0);
        trraList.add(trra);
        return trra;
    }
    //创建行
    private LinearLayout createRow(int sIndex, int eIndex){
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,1);

        for(int i=sIndex;i<eIndex;i++){
            switch(rraList.get(i).getitemType()){
                case "文本":
                    linearLayout.addView(createTV(rraList.get(i).getname()), params);
                    break;
                case "多选":
                    linearLayout.addView(createCB(rraList.get(i).getname(), getTrra(rraList.get(i))), params);
                    break;
                case "单选":
                    linearLayout.addView(createSelector(i, getTrra(rraList.get(i))), params);
                    break;
                case "输入框":
                case "富文本":
                    return createInput(rraList.get(i), getTrra(rraList.get(i)));
            }
        }

        return linearLayout;
    }
    //创建附加项
    private void initRowAdd(){
        try {
            rraList = db.selector(r_reportrowAddtion.class).where("rowid", "=", minorId).orderBy("orderValue").findAll();
            trraList = db.selector(r_trrAddtion.class).where("schid","=",schid).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(rraList==null||rraList.size()<1){
            return;
        }
        markScore.setHint("分数由附加项决定");
        markScore.setFocusable(false);
        markScore.setOnClickListener(null);
        scoreType = 2;
        if(trraList==null){
           trraList = new ArrayList<>();
        }
        int insertIndex = contentLayout.indexOfChild(submitBtn);
        TextView titleView=new TextView(this);
        titleView.setText("附加文字");
        titleView.setTextSize(15);
        titleView.setTextColor(getResources().getColor(R.color.titleColor));
        //titleView.getPaint().setFakeBoldText(true);
        titleView.setPadding(3,3,3,3);
        titleView.setBackgroundColor(getResources().getColor(R.color.white));
        contentLayout.addView(titleView, insertIndex);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setBackgroundColor(getResources().getColor(R.color.white));

        //根据itemType和endStr，逐行添加View
        int sIndex = 0;//每行起始View的索引
        for(int i=0;i<rraList.size();i++){
            switch(rraList.get(i).getitemType()){
                case "文本":
                case "多选":
                case "单选":
                    if(rraList.get(i).getendStr().equals("br")){
                        linearLayout.addView(createRow(sIndex,i+1));
                        linearLayout.addView(createDividing());
                        sIndex = i+1;
                    }else if(i == rraList.size()-1){
                        linearLayout.addView(createRow(sIndex,i+1));
                    }
                    break;
                case "输入框":
                case "富文本":
                    if(sIndex<i)
                        linearLayout.addView(createRow(sIndex,i));
                    linearLayout.addView(createRow(i,i+1));
                    if(rraList.get(i).getendStr().equals("br"))
                        linearLayout.addView(createDividing());
                    sIndex = i+1;
                    break;
                default:
                    sIndex = i+1;
            }
        }

        LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(15,15,15,15 );
        contentLayout.addView(linearLayout, insertIndex+1, layoutParams);
    }
    //endregion

    private List<RMain.TablesBean.RowsBean.RItemsBean> getItemsByRrowid(int rowid, ArrayList<RMain> rMains) {
        List<RMain.TablesBean.RowsBean.RItemsBean> itemList = null;
        for (int i = 0; i < rMains.size(); i++) {
            List<RMain.TablesBean> tb = rMains.get(i).getTables();
            for (RMain.TablesBean t : tb) {
                List<RMain.TablesBean.RowsBean> rbs = t.getRows();
                for (RMain.TablesBean.RowsBean rb : rbs) {
                    if (rb.getQ2().getID() == rowid) {
                        itemList = rb.getRItems();
                        break;
                    }
                }
            }
        }
        return itemList;
    }

    private double getMaxScoreByRrowid(int rowid, ArrayList<RMain> rMains) {
        double maxscore = 0;
        for (int i = 0; i < rMains.size(); i++) {
            List<RMain.TablesBean> tb = rMains.get(i).getTables();
            for (RMain.TablesBean t : tb) {
                List<RMain.TablesBean.RowsBean> rbs = t.getRows();
                for (RMain.TablesBean.RowsBean rb : rbs) {
                    if (rb.getQ2().getID() == rowid) {
                        maxscore = rb.getQ2().getMaxScore();
                        break;
                    }
                }
            }
        }
        return maxscore;
    }


    /**
     * 判断目录是否存在，不存在则创建改文件夹
     */
    public void checkPhotoPathExist() {

        File file = new File(pubClass.pictureSavePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 设置图片listview中的数据
     *
     * @param adapter 适配器
     * @param fileStr 文件路径
     */
    public void setListViewData(AddPhotoAdapter adapter, String fileStr) {
        photoList = splitListViewPicString(fileStr);
        adapter.setListData(photoList);
        adapter.notifyDataSetInvalidated();
    }

    /*设置视频listView的数据*/
    public void setVideoListData(AddVideoAdapter videoAdapter, String fileString) {
        videoList = splitListViewPicString(fileString);
        videoAdapter.setListData(videoList);
        videoAdapter.notifyDataSetInvalidated();
    }
    /**
     * 拆分图片的路径，并添加到listview中
     *
     * @param fileString
     * @return
     */
    public List<String> splitListViewPicString(String fileString) {
        String[] everyPicFile = fileString.split(",");
        List<String> imgList = new ArrayList<String>();
        for (String everyPic : everyPicFile) {
            if (!TextUtils.isEmpty(everyPic)) {
                imgList.add(everyPic);
            }
        }
        return imgList;
    }


    /*图片的点击*/
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        checkPhotoPathExist();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss",Locale.getDefault());
        newPhotoName = "yxd" + sdf.format(new Date());
        resultPath =  pubClass.pictureSavePath + newPhotoName + ".jpg";
        int count = adapter.getCount();
        if (position ==0) {
            if (count<9){
                showPop();
            }else{
                BaseActivity.showAnimaDialog(MarkPhotoActivity.this,"照片已达最大限制");
            }

        }else{
//            String path= (String) parent.getItemAtPosition(position-1);
//            startActivity(new Intent(this,ImgDetailActivity.class).putExtra("filepath",path));
            //拿到photoList ,及position
            StringBuilder jpgStr= new StringBuilder();
            for (int k=0;k<photoList.size();k++){
                jpgStr.append(photoList.get(k)).append(",");
            }
            startActivity(new Intent(this,ImageViewPagerActivity.class)
                    .putExtra("filepath", jpgStr.toString())
                    .putExtra("position",position-1));
        }
    }

    /**
     * 图片长按删除
     *
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (position != 0) {
            DelPicListItem(position-1);
        }

        return false;
    }

    private void DelPicListItem(final int position) {

        MaterialDialogUtils.showMaterialDialog(this, "是否删除照片", "确定", "取消", true,false, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                String newAllFileList = "";
                photoList.remove(position);
                for (int i = 0; i < photoList.size(); i++) {
                    newAllFileList += photoList.get(i) + ",";
                }
                allPhotoFileString = newAllFileList;
                adapter.setListData(photoList);
                adapter.notifyDataSetChanged();
            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }
    private void DelVideoListItem(final int position) {
        MaterialDialogUtils.showMaterialDialog(this, "是否删除视频", "确定", "取消", true,false, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                String newAllvideoFile="";
                videoList.remove(position);
                for (int i=0;i<videoList.size();i++){
                    newAllvideoFile+=videoList.get(i)+",";
                }
                allVideoFileString=newAllvideoFile;
                videoAdapter.setListData(videoList);
                videoAdapter.notifyDataSetChanged();
            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submitInfo://提交
                submitAllInfo();
                break;
            case R.id.markScore://分数
                dialog = new Dialog(this);
                if (scoreType == 1) {
                    View view = LayoutInflater.from(this).inflate(R.layout.scoretype1_dialog, (ViewGroup) getWindow().getDecorView(),false);
                    TextView listTitle = (TextView) view.findViewById(R.id.listTitle);
                    listTitle.setText("评分");
                    ListView myScoreList = (ListView) view.findViewById(R.id.myList);
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog.setContentView(view);
                    ItemScoreAdapter scoreAdapter = new ItemScoreAdapter(MarkPhotoActivity.this, scoreList);
                    myScoreList.setAdapter(scoreAdapter);
                    myScoreList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            RMain.TablesBean.RowsBean.RItemsBean bean = (RMain.TablesBean.RowsBean.RItemsBean) parent.getItemAtPosition(position);
                            scoreId = bean.getID();
                            markScore.setText(String.valueOf(bean.getScore()));
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                } else {
                    View view = LayoutInflater.from(this).inflate(R.layout.input_text_dialog, (ViewGroup) getWindow().getDecorView(),false);
                    this.inputScore = (EditText) view.findViewById(R.id.inputScore);
                    inputScore.setFilters(new InputFilter[] { lengthfilter });
                    inputScore.setHint("最大分数"+MaxScore);
                    TextView btnCanel = (TextView) view.findViewById(R.id.btnCanel);
                    TextView action_ok = (TextView) view.findViewById(R.id.action_ok);
                    btnCanel.setOnClickListener(this);
                    action_ok.setOnClickListener(this);
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog.setContentView(view);
                    dialog.show();
                }
                break;
            case R.id.btnCanel:
                dialog.dismiss();
                break;
            case R.id.action_ok:
                String text = inputScore.getText().toString().trim();
                if (!TextUtils.isEmpty(text) && Double.parseDouble(text) > MaxScore) {
                    Toast.makeText(this, "请输入小于等于" + MaxScore + "的分数", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(text)) {
                    Toast.makeText(this, "请输入评分", Toast.LENGTH_SHORT).show();
                } else {
                    markScore.setText(text);
                    dialog.dismiss();
                }
                break;
        }
    }


    public void showExitDialog(){
        new MaterialDialog.Builder(this)
                .content("是否放弃评估项编辑")
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(this,R.color.blue))
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this,R.color.color_theme))
                .canceledOnTouchOutside(true)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .build()
                .show();
    }
    InputFilter lengthfilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };

    //计算多选得分
    private double getCBScore(int sIndex, int eIndex){
        double ret = trraList.get(sIndex).getstep();
        for(int i=sIndex;i<eIndex;i++){
            if(trraList.get(i).getischecked()>0){
                ret+=trraList.get(i).getmin();
            }
        }
        if(ret<0)
            ret=0;
        return ret*trraList.get(sIndex).getrights();
    }

    /**
     * 确定保存到本地，条件至少输入其中的一项数据
     */
    public void submitAllInfo() {
        /*描述和图片视频至少一个上传*/
        int photopass = 1;
        int descpass = 1;
        int videopass = 1;
        String desc = markDesc.getText().toString().trim();

        if (photoList == null || photoList.size() == 0) {
            photopass = 0;
        }
        if (TextUtils.isEmpty(desc)) {
            descpass = 0;
        }
        if (videoList==null||videoList.size()==0){
            videopass = 0;
        }

        if(rraList!=null && rraList.size()>0){
            if(trraList!=null){
                double rra_score = 0;
                int orderValue = 0,sIndex = 0;
                for(int i=0;i<trraList.size();i++){
                    View view = trraList.get(i).getview();
                    if(view instanceof CheckBox){
                        trraList.get(i).setischecked(((CheckBox) view).isChecked() ? 1 : 0);
                        if(trraList.get(i).getorderValue()!=orderValue){
                            if(orderValue > 0)
                                rra_score += getCBScore(sIndex,i);
                            orderValue = trraList.get(i).getorderValue();
                            sIndex = i;
                        }
                    }else{
                        if(orderValue > 0){
                            rra_score += getCBScore(sIndex,i);
                            orderValue = 0;
                        }
                        if(view instanceof EditText){
                            trraList.get(i).setitemValue(((EditText) view).getText().toString());
                            if(trraList.get(i).getrights()>0){
                                String text = trraList.get(i).getitemValue();
                                if(text == null || TextUtils.isEmpty(text)){
                                    Toast.makeText(this, "附加项["+trraList.get(i).getname()+"]评分未输入", Toast.LENGTH_SHORT).show();
                                    return;
                                }else{
                                    double etScore = Double.parseDouble(text);
                                    if(etScore>trraList.get(i).getmax() || etScore<trraList.get(i).getmin()){
                                        Toast.makeText(this, "附加项["+trraList.get(i).getname()+"]评分输入不正确", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    rra_score += etScore*trraList.get(i).getrights();
                                }
                            }
                        }
                        else if(view instanceof Spinner){
                            r_rrowAddtion_item rra_i = (r_rrowAddtion_item)((Spinner) view).getSelectedItem();
                            trraList.get(i).setr_rrItemId(rra_i.getId());
                            rra_score += rra_i.getscore()*trraList.get(i).getrights();
                        }
                    }
                }
                markScore.setText(String.valueOf(rra_score));
                Log.i("rralist","markScore="+markScore.getText().toString());
                try {
                    db.saveOrUpdate(trraList);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }

        score = markScore.getText().toString();

        if (TextUtils.isEmpty(score)) {
            new MaterialDialog.Builder(this)
                    .content("请输入评分")
                    .positiveColor(ContextCompat.getColor(this,R.color.blue))
                    .positiveText("确定")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .build()
                    .show();
            return;
        }
        if (descpass == 0 && photopass == 0 &&videopass == 0) {
            new MaterialDialog.Builder(this)
                    .content("请输入照片、视频或描述以便备注，谢谢")
                    .positiveColor(ContextCompat.getColor(this,R.color.blue))
                    .positiveText("确定")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .build()
                    .show();
            return;
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.getDefault());
        String currentDate = sdf.format(date);

        /*判断评分类型*/
        if (scoreType == 1) {
            if (tag == 1) {//tag新增
                rr = new tempLostRR(
                        MainActivity.id,
                        schid,
                        minorId,
                        Double.parseDouble(score),
                        scoreId,
                        currentDate,
                        desc,
                        allPhotoFileString,
                        title,
                        scoreType,allVideoFileString,true);
                rr.setSelectItemId(scoreId);
                try {
                    if(rr.getSelectItemId()!=0) {
                        db.saveOrUpdate(rr);
                        Toast.makeText(MarkPhotoActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                      //  CacheActivity.finishActivity();
                        if (ispoint==2){
                            finish();
                        }else{
                         //   startActivity(new Intent(MarkPhotoActivity.this, WrittingEvaluationListActivity.class).putExtra("rrschid",schid));
                            finish();
                        }
                    }
                    else
                    {
                        Toast.makeText(this, "请选择评分项", Toast.LENGTH_SHORT).show();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {//编辑
                //score=String.valueOf(score);
                title = rr.getRowName();
                minorId = rr.getRRowId();
                rr = new tempLostRR(_ID, MainActivity.id,schid, minorId, Double.parseDouble(score), scoreId, currentDate, desc, allPhotoFileString, title, scoreType,allVideoFileString);
                try {
                    if(rr.getSelectItemId()!=0) {
                        db.saveOrUpdate(rr);
                        Toast.makeText(MarkPhotoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    //    CacheActivity.finishActivity();
                        if (ispoint==2){
                            finish();
                        }else{
                         //   startActivity(new Intent(MarkPhotoActivity.this, WrittingEvaluationListActivity.class).putExtra("rrschid",schid));
                            finish();
                        }
                    }
                    else
                    {
                        Toast.makeText(this, "请选择评分项", Toast.LENGTH_SHORT).show();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
        /*评分类型2*/
        else {
            if (tag == 1) {//新增
//                tempLostRR newRR=new tempLostRR();
//                newRR.setEmpId(MainActivity.id);
//                newRR.setSchId(YxdEvaluationListActivity.schid);
//                newRR.setSelectItemId(minorId);
//                newRR.setScore(Double.parseDouble(score));

                rr = new tempLostRR(
                        MainActivity.id,
                        schid,
                        minorId,
                        Double.parseDouble(score),
                        scoreId,
                        currentDate,
                        desc,
                        allPhotoFileString,
                        title,
                        scoreType,
                        allVideoFileString,
                        true
                );
                try {
                    if(!TextUtils.isEmpty(score)) {
                        db.saveOrUpdate(rr);
                        Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                        //CacheActivity.finishActivity();
                    //    startActivity(new Intent(MarkPhotoActivity.this, WrittingEvaluationListActivity.class).putExtra("rrschid",schid));
                        finish();
                    }
                    else
                    {
                        Toast.makeText(this, "请选择评分项", Toast.LENGTH_SHORT).show();
                    }

                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {//编辑
                title = rr.getRowName();
                minorId = rr.getRRowId();
                /*查询当前的rowid的最大分数*/
                //score=String.valueOf(score);

                rr = new tempLostRR(
                        _ID,
                        MainActivity.id,
                        schid,
                        minorId,
                        Double.parseDouble(score),
                        scoreId,
                        currentDate,
                        desc,
                        allPhotoFileString,
                        title,
                        scoreType,
                        allVideoFileString);
                try {
                    if(!TextUtils.isEmpty(score)) {
                        tempLostRR temp = new tempLostRR();
                        db.saveOrUpdate(rr);
                        temp = db.selector(tempLostRR.class).where("_ID", "=", _ID).findFirst();
                        if (temp != null) {
                            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                         //   CacheActivity.finishActivity();
                         //   startActivity(new Intent(MarkPhotoActivity.this, WrittingEvaluationListActivity.class).putExtra("rrschid",schid));
                            finish();
                        } else {
                            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    else
                    {
                        Toast.makeText(this, "请选择评分项", Toast.LENGTH_SHORT).show();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    public void getVideoPath() {
        PlayVideoActiviy.setOnPickFinishListener(new PlayVideoActiviy.PickFinishListener() {
            @Override
            public void onPickFinish(String path) {
                BaseActivity.showAnimaDialog(MarkPhotoActivity.this,"视频保存在"+"\n"+path);
                Log.i("videoPath=", path);
                allVideoFileString+=path+",";
                setVideoListData(videoAdapter,allVideoFileString);
            }
        });
    }

    //返回键监听

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode==KeyEvent.KEYCODE_BACK){
            showExitDialog();

        }
        return super.onKeyDown(keyCode, event);
    }

    //接受网络状态的判断广播
    NetWorkStateReceiver netWorkStateReceiver;
    int whetherConnectNetWork=0;
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
        super.onPause();
    }

    //用于离线状态下的voice的点击
    class NetWorkStateReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (mConnectivityManager!=null){
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo!=null){
                    whetherConnectNetWork=1;
                    voiceIn.setEnabled(true);
                }else{
                    whetherConnectNetWork=0;
                    voiceIn.setEnabled(false);
                }
            }
        }
    }

    //showPop
    Dialog popDialog;
    boolean isMultiSelector=true;
    final int REQUEST_CODE_GALLERY=1000;
    final  int REQUEST_CODE_CARMEAR=1001;
    final int REQUEST_TAKE_VIDEO_CODE =1002 ;

    public void showPop(){
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (inflater!=null){
            View holder = inflater.inflate(R.layout.view_popup_button,
                    (ViewGroup) getWindow().getDecorView(), false);
            View gallery = holder.findViewById(R.id.btnPhoto);
            View capture = holder.findViewById(R.id.btnCapture);
            View cancel = holder.findViewById(R.id.btnCanel);

            ButtonClick click = new ButtonClick();
            gallery.setOnClickListener(click);// 图库选择
            capture.setOnClickListener(click);// 拍照选择
            cancel.setOnClickListener(click);// 取消
            popDialog= PopupUtil.makePopup(this,holder);
            popDialog.show();
        }
    }

    public class ButtonClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {

            if (popDialog!=null){
                popDialog.dismiss();
            }

            if (v.getId() == R.id.btnPhoto) {// 图库选取
                checkTakeMediaPermission(R.id.btnPhoto);
            }

            if (v.getId() == R.id.btnCapture) {// 拍照
                checkTakeMediaPermission(R.id.btnCapture);
            }
            if (v.getId() == R.id.btnVideo){//视频录制
                checkTakeMediaPermission(R.id.btnVideo);

            }


            if (v.getId()==R.id.btn_cancel){
                popDialog.dismiss();
            }
        }
    }
//返回的结果
ProgressDialog waterDialog;
    private GalleryFinal.OnHanlderResultCallback myResultCallBack=new GalleryFinal.OnHanlderResultCallback() {

        @Override
        public void onHanlderSuccess(int reqeustCode, final List<PhotoInfo> resultList) {

            waterDialog=new ProgressDialog(MarkPhotoActivity.this);
            waterDialog.setMessage("图片处理中，请稍后");
            waterDialog.show();
            Thread t=new Thread(String.valueOf(Looper.getMainLooper())){
                @Override
                public void run() {
                    for (int i=0;i<resultList.size();i++) {
                        String path = resultList.get(i).getPhotoPath();
                        WindowManager winManager = getWindowManager();
                        DisplayMetrics metrics = new DisplayMetrics();
                        winManager.getDefaultDisplay().getMetrics(metrics);
                        Bitmap mBitmap = BitmapUtils.getBmpFromFile(path,
                                metrics.widthPixels, metrics.heightPixels, null);
                        try {
                            mBitmap.compress(Bitmap.CompressFormat.JPEG, 60, new FileOutputStream(path));
//                            int width = mBitmap.getWidth();
//                            int height = mBitmap.getHeight();
                            //加水印后的bitmap
                            //   Bitmap cropBitmap=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
                           // mBitmap = creatBitmap(mBitmap);
                            mBitmap=creatMyBitmap(mBitmap);
                            //将图片保存在本地指定路径
                            checkPhotoPathExist();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss",Locale.getDefault());
                            Random random = new Random();
                            String fileName2 = String.valueOf(random.nextInt(Integer.MAX_VALUE));
                            newPhotoName = "yxd" + sdf.format(new Date()) + fileName2;
                            resultPath =pubClass.pictureSavePath + newPhotoName + ".jpg";
                            //流保存
                            File file = new File(resultPath);
                            FileOutputStream outputStream = null;
                            try {
                                outputStream = new FileOutputStream(file);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
                            try {
                                if (outputStream!=null){
                                    outputStream.flush();
                                    outputStream.close();
                                    mBitmap.recycle();
                                }
                                //保存图片后发送广播通知更新数据库
                                Uri uri = Uri.fromFile(file);
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                allPhotoFileString += resultPath + ",";

                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    Message msg=new Message();
                    msg.what=0;
                    mHandler.sendMessage(msg);

                }
            };
            t.start();

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(MarkPhotoActivity.this,"图片获取失败",Toast.LENGTH_SHORT).show();
        }
    };
    //接收消息更新ui
    public static class iHandler extends Handler{

        private WeakReference<MarkPhotoActivity> mActivity;
        iHandler(MarkPhotoActivity activity){
            mActivity = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                //图片水印完毕
                mActivity.get().waterDialog.dismiss();
                mActivity.get().deleteDir();
                mActivity.get().setListViewData( mActivity.get().adapter,  mActivity.get().allPhotoFileString);
            }
        }
    }

    //由于第三方框架无法改变存储路径，因此将拍照保存的文件删除
    public void deleteDir(){
        //文件路径
        String path=Environment.getExternalStorageDirectory()+"/DCIM"+"/GalleryFinal";
        File file=new File(path);
        if (!file.exists() || !file.isDirectory()){
            return;
        }
        for (File dir:file.listFiles()){
            if (dir.isFile()){
                dir.delete();
            }else if (dir.isDirectory()){
                //递归删除
                deleteDir();
            }
            //删除目录
            file.delete();
        }
    }

    public Bitmap creatMyBitmap(Bitmap src){
//        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        int WW = metrics.widthPixels;
//        int WH = metrics.widthPixels;
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAlpha(60);
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap newBit=Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBit);
        canvas.drawBitmap(src,0,0,null);
        //创建一个矩形，将文字放入矩形中
        RectF rect=new RectF(30,h-160,450,h-30);
        canvas.drawRoundRect(rect,30,30,paint);
        //绘制文字
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setTextSize(36);
        paint.setAntiAlias(true);
        String date= BaseActivity.getNowDate();
        canvas.drawText(date,60,h-110,paint);
        canvas.drawText(shopName,60,h-65,paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newBit;
    }

    public Bitmap creatBitmap(Bitmap src){
        //绘制要显示的水印图,然后将水印的bitmap显示在上面
        Bitmap bitmap=Bitmap.createBitmap(250,50, Bitmap.Config.ARGB_8888);
        //构建画板
        Canvas canvas=new Canvas(bitmap);
        //设置画板图片背景
        canvas.drawBitmap(bitmap,0,0,null);
        canvas.drawColor(Color.WHITE);
        //创建画笔，绘制文字
        Paint paint=new Paint();
        paint.setTextSize(20);
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        String date= BaseActivity.getNowDate();
        canvas.drawText(date,40,20,paint);
        canvas.drawText(shopName,40,45,paint);
        Bitmap localBit=BitmapFactory.decodeResource(getResources(),R.mipmap.icon_location_small);
        canvas.drawBitmap(localBit,10,20,null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        //绘制好了，然后放入最终的bitmap中
        int w=src.getWidth();
        int h=src.getHeight();
        Paint mpaint=new Paint();
        mpaint.setAntiAlias(true);
        Bitmap newBit=Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
        Canvas canvas1=new Canvas(newBit);
        canvas1.drawBitmap(src,0,0,null);
        canvas1.drawBitmap(bitmap,20,h-50,mpaint);
        canvas1.save(Canvas.ALL_SAVE_FLAG);
        canvas1.restore();
        return newBit;
    }

    //设置bitmap的透明度
    public static Bitmap setAlplaBitmap(Bitmap sourceImg, int number) {
        int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
        sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg.getWidth(), sourceImg.getHeight());
        number = number * 255 / 100;
        for (int i = 0; i < argb.length; i++) {
            argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF);
        }
        sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Bitmap.Config.ARGB_8888);

        return sourceImg;
    }

    public  void saveBitmap(Bitmap mBitmap){
        //获取内部存储状态
        String state = Environment.getExternalStorageState();
//如果状态不是mounted，无法读写
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this,"无法获取图片",Toast.LENGTH_SHORT).show();
        }
    }

    //拍摄视屏
    private void showVideoPop(){
        LayoutInflater inflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (inflater!=null){
            View holder=inflater.inflate(R.layout.view_popup_button2,null,false);
            View cancle=holder.findViewById(R.id.btnCanel);
            View video=holder.findViewById(R.id.btnVideo);

            ButtonClick click = new ButtonClick();
            cancle.setOnClickListener(click);
            video.setOnClickListener(click);
            popDialog=PopupUtil.makePopup(this,holder);
            popDialog.show();
        }
    }


    /*权限的获取*/
    private void checkTakeMediaPermission(int typeid) {
        int permissionState_Camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int permissionState_Storage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionState_Audio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (permissionState_Camera != PackageManager.PERMISSION_GRANTED || permissionState_Storage != PackageManager.PERMISSION_GRANTED
                || permissionState_Audio != PackageManager.PERMISSION_GRANTED) {
            // 用户已经拒绝过一次，给用户解释提示对话框
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                // 展示自定义提醒框
                new MaterialDialog.Builder(this)
                        .content("你必须允许相应权限")
                        .positiveText("确定")
                        .positiveColor(getResources().getColor(R.color.blue))
                        .negativeText("取消")
                        .negativeColor(getResources().getColor(R.color.color_theme))
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                PermissionUtil.requestPermissionForCamera(MarkPhotoActivity.this);
                            }

                        })
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .build()
                        .show();
            }else{
                PermissionUtil.requestPermissionForCamera(this);
            }
        }else{
            if(typeid==R.id.btnVideo)
                skipToVideoTaker();
            else if(typeid==R.id.btnCapture) {
                YXDAPP.GallerySet(getSelectJpgCount(),this);
                GalleryFinal.openCamera(REQUEST_CODE_CARMEAR, YXDAPP.functionConfig, myResultCallBack);
            }
            else if(typeid==R.id.btnPhoto)
            {
                if (isMultiSelector){
                    YXDAPP.GallerySet(getSelectJpgCount(),this);
                    GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }else{ //选取头像
                    if (getSelectJpgCount()==0){
                        Toast.makeText(this,"选取的照片达到最大数量,长按可删除照片",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }
            }
        }
    }
    /*跳转到拍摄*/
    private void skipToVideoTaker(){
        startActivityForResult(new Intent(this, RecorderActivity.class),REQUEST_TAKE_VIDEO_CODE);
    }
    /*计算选取的照片的额数量*/
    public int getSelectJpgCount(){
        if (TextUtils.isEmpty(allPhotoFileString)){
            return 9;
        }
        String[] array = allPhotoFileString.split(",");
        if (array.length<9){
            return 9-array.length;
        }else{
            return 0;
        }

    }

    private void methodRequiresPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            Log.i("yxdPermissions", "Already have permission!");
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "申请摄像头、录音、储存卡权限", PermissionUtil.CAMERA_STATE_REQUEST_CODE, perms);
        }
    }
    /*判断权限是否存在*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        /*
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
            Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
        }*/
    }



    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted
        Log.i("yxdPermissions", "onPermissionsGranted:" + requestCode + ":" + list.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        Log.i("yxdPermissions", "onPermissionsDenied:" + requestCode + ":" + list.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, list)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}